package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"xueyuan_backend/model"
	"xueyuan_backend/service"
)

type ApiResp struct {
	Items		[]ApiArticle		`json:"items"`
	Total		int					`json:"total"`
	Page		int					`json:"page"`
	Size 		int					`json:"size"`
}

type ApiArticle struct {
	Title string			`json:"title"`
	Date  string		`json:"published_at"`
	Content string			`json:"content"`
	Photos []string				`json:"photos"`
	Url 	string		`json:"url"`
}

func main()(){
	GetApiArticles("cs")
	GetApiArticles("sw")
}

// GetApiArticles 按学院调接口
func GetApiArticles(institution string)(articles []model.SaveArticle){
	url := "http://47.108.67.131/news_api/v1/items/%s/%s?page=%d&size=20"
	// 新闻
	var newsArticles []model.SaveArticle
	newsArticles = GetApiArticlesOnColumn("news",url,institution)
	// 通知
	var noticeArticles []model.SaveArticle
	noticeArticles = GetApiArticlesOnColumn("notices",url,institution)

	articles = append(articles,newsArticles...)
	articles = append(articles,noticeArticles...)

	return articles
}

func GetApiArticlesOnColumn(column string,originUrl string,institution string)(articles []model.SaveArticle){
	var db = service.ConnectDb()
	for page := 1; ; page++{
		// 合成url
		url := fmt.Sprintf(originUrl, institution, column, page)
		fmt.Println(url)
		// 创建http get请求
		resp,err := http.Get(url)
		if err != nil {
			return nil
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body) // response.Body 是一个数据流
		msg := string(body)            // 将 io数据流转换为string类型
		//string转json
		var apiResp ApiResp

		if err := json.Unmarshal([]byte(msg), &apiResp); err == nil {
			for _,i := range apiResp.Items{
				var article model.SaveArticle
				article.Date = i.Date
				article.Title = i.Title
				article.Content = i.Content
				if len(i.Photos) != 0{
					article.PicLink = i.Photos[0]
				}
				article.ArticleUrl = i.Url
				if institution == "cs"{
					article.SourceName = "计算机学院"
				}
				if institution == "sw"{
					article.SourceName = "软件学院"
				}

				db.Table("article").Create(&article)
				articles = append(articles,article)
			}
			//计算总页数
			pageMax := int(float32(apiResp.Total/20)+0.5)
			fmt.Println(pageMax)
			if page == pageMax{
				break
			}
		} else {
			fmt.Println(err)
		}
	}
	return articles
}